package utils;

import com.mohamnag.fxwebview_debugger.DevToolsDebuggerServer;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;

/**
 * @author: Administrator
 * @date: 2021/03/13 23:36
 * @description:
 */
public class WebViewUtil {
    private static WebViewUtil webViewUtil;
    public static WebViewUtil getInstance(){
        if(webViewUtil==null){
            webViewUtil = new WebViewUtil();
        }
        return webViewUtil;
    }


    public WebEngine webEngine;
    public WebEngine initCenterWebView(WebView centerWebView, String pageName) {
        //获取Engine
        if (webEngine==null){
            webEngine = centerWebView.getEngine();
        }
        try {
            int debugPort = 51742;
                DevToolsDebuggerServer.startDebugServer(webEngine.impl_getDebugger(), debugPort);
                com.sun.javafx.webkit.WebConsoleListener.setDefaultListener(new com.sun.javafx.webkit.WebConsoleListener() {
                    @Override
                    public void messageAdded(WebView webView, String message, int lineNumber, String sourceId) {
                        System.out.println("Console: " + message + " [" + sourceId + ":" + lineNumber + "] ");
                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
        }

        webEngine.setJavaScriptEnabled(true);
        //获取当前Java版本
        System.out.println("Java Version:" + System.getProperty("java.runtime.version"));
        //获取当前JavaFx版本
        System.out.println("JavaFXersion:" + System.getProperty("javafx.runtime.version"));
        //获取当前系统版本
        System.out.println("OS:" + System.getProperty("os.name") + "," + System.getProperty("os.arch"));
        //获取WebKit内核版本
        System.out.println("User Agent:" + centerWebView.getEngine().getUserAgent());
        //获取页面路径
        String mainUrl = getClass().getResource("/pages/layout/"+pageName).toExternalForm();
        //获取页面alert弹窗和重新加载页面
        centerWebView.getEngine().setOnAlert((WebEvent<String> wEvent) -> {
            //打印页面弹窗
            System.out.println("Alert Event  -  Message:  " + wEvent.getData());
            if (wEvent.getData().equals("Awesome123123")) {
                //重新加载页面
                webEngine.load(getClass().getResource("/pages/layout/test.html").toExternalForm());
            }
            if (wEvent.getData().equals("123")) {
                webEngine.load(getClass().getResource("/pages/layout/demo.html").toExternalForm());
            }
        });
        //初始化
        webEngine.load(mainUrl);
        return webEngine;
    }
}
